package com.neulogistics.core.customercenter.infrastructure.persistence.converter;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.neulogistics.core.customercenter.domain.model.aggregate.Order;
import com.neulogistics.core.customercenter.domain.model.enumeration.OrderStatus;
import com.neulogistics.core.customercenter.domain.model.enumeration.OrderType;
import com.neulogistics.core.customercenter.domain.model.valueobject.Address;
import com.neulogistics.core.customercenter.domain.model.valueobject.OrderItem;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.po.OrderPO;
import org.springframework.beans.BeanUtils;


public class OrderEntityPOConverter {
    private static final int Rate = 100;

    public static OrderPO entityToPO(Order order){
        if(order == null)
            return null;

        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(order, orderPO);
        ;
        // 枚举对象赋值
        if(order.getOrderType() != null){
            orderPO.setOrderType(order.getOrderType().id);
        }
        if(order.getOrderStatus() != null){
            orderPO.setOrderStatus(order.getOrderStatus().id);
        }
        // 值对象转换为json对象
        if(order.getReceiverAddress() != null){
            orderPO.setReceiverAddress(JSONUtil.parseObj(order.getReceiverAddress()));
        }
        if(order.getOrderItems() != null){
            orderPO.setOrderItems(JSONUtil.parseArray(order.getOrderItems()));
        }
        // 价格转换
        if(order.getTotalAmount() != null){
            orderPO.setTotalAmount((int) (order.getTotalAmount() * Rate));
        }

        return orderPO;
    }

    public static Order POToEntity(OrderPO orderPO){
        if(orderPO == null)
            return null;

        Order order = new Order();
        // 复制普通属性, id是可以在这里被复制进去的
        BeanUtils.copyProperties(orderPO, order);
        // json对象转换为值对象
        order.setReceiverAddress(JSONUtil.toBean(orderPO.getReceiverAddress(), Address.class));
        order.setOrderItems(JSONUtil.toList(orderPO.getOrderItems(), OrderItem.class));
        // 枚举值转换
        order.setOrderType(OrderType.fromValue(orderPO.getOrderType(), OrderType.class));
        order.setOrderStatus(OrderStatus.fromValue(orderPO.getOrderStatus(), OrderStatus.class));
        // 价格转换
        order.setTotalAmount(Double.valueOf(orderPO.getTotalAmount()) / Rate);

        return order;
    }
}
